require(["config"], function() {
    require(["jquery", "template", "header", "zoom", "fly", "cookie"], function($, template) {
        function Detail() {
            this.render();
        }

        Detail.prototype = {
            constructor: Detail,
            render: function() {
                $.ajax("http://rap2api.taobao.org/app/mock/data/515959")
                    .done($.proxy(this.handleData, this));
            },
            handleData: function(data) {
                data = data.res_body.data;
                var html = template("detail_template", data);
                $(".content_box").prepend(html);
                this.zoom();
                this.addListener();
            },
            zoom: function() {
                $(".middle-zoom").elevateZoom({
                    gallery:'gal1',
                    cursor: 'pointer',
                    galleryActiveClass: 'active'
                });
            },
            addListener: function() {
                $(".buy").click(this.addToCartHandler);
            },
            // 添加到购物车处理
            addToCartHandler: function(event) {
                var currentProduct = {
                    id: $(".hiddenid").text(),
                    title: $(".title").text(),
                    img: $("#gal1 img:first").attr("src"),
                    price: $(".price").text(),
                    amount:1
                };
                console.log(currentProduct);
                $.cookie.json = true;
                var products = $.cookie("cart") || [];
                var has = products.some(function(prod) {
                    if (prod.id == currentProduct.id) {
                        prod.amount++; // 数量自增
                        return true;
                    }
                    return false;
                });
                if (!has)
                    products.push(currentProduct);

                // 保存购物车cookie
                $.cookie("cart", products, {expires: 10, path:"/"});

                // 抛物线效果
                var end = $(".cart").offset();
                end.top -= $(window).scrollTop();
                var start = {top: event.pageY - $(window).scrollTop(), left: event.pageX};
                var flyer = $("#gal1 img:first").clone();
                flyer.fly({
                    start,
                    end,
                    onEnd: function() {
                        this.destroy();
                    }
                });

                return false;
            }
        }

        new Detail();
    });
});